#include<string>
#include<vector>
#include<array>
#include<unordered_map>
#include<algorithm>
#include<limits>
#include <stack>
#include<iostream>
#include<sstream>
#include<deque>
#define MOD 1000000007
class Solution {
public:
    int largestIsland(std::vector<std::vector<int>>& grid) {
        int n = grid.size();
        int m = grid[0].size();
        int id =2;
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                dfs(grid,i,j,n,m,id++);
            }
        }
        std::vector<int> size (id,0);
        int ans = 0;
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                if (grid[i][j] == 0) continue;
                ans = std::max(ans,++size[grid[i][j]]);
            }
        }
        std::vector<bool> visited(id,false);
        int merge = 1;
        int up=0,down=0,left=0,right=0;
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                if(grid[i][j]!=0)
                    continue;
                merge = 1;
                up = i-1>=0?grid[i-1][j]:0;
                down = i+1<n?grid[i+1][j]:0;
                left = j-1>=0?grid[i][j-1]:0;
                right = j+1<m?grid[i][j+1]:0;
                visited[up] = true;
                merge+=size[up];
                if (!visited[down])
                {
                    merge+=size[down];
                    visited[down] = true;
                }
                if (!visited[left])
                {
                    merge+=size[left];
                    visited[left] = true;
                }
                if (!visited[right])
                {
                    merge+=size[right];
                    visited[right] = true;
                }
                ans = std::max(ans,merge);
                visited[up] = false;
                visited[down] = false;
                visited[left] = false;
                visited[right] = false;
            }
        }
        return ans;
    }
    void dfs(std::vector<std::vector<int>>& board,const int& i,const int& j,const int& n,const int &m,const int& id)
    {
        if (i<0||i>=n||j<0||j>=m||board[i][j]!=1)
        {
            return;
        }
        board[i][j]=id;
        dfs(board,i+1,j,n,m,id);
        dfs(board,i-1,j,n,m,id);
        dfs(board,i,j+1,n,m,id);
        dfs(board,i,j-1,n,m,id);
    }
};